<template>
  <div class="import-export-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>数据导入导出</h2>
      <p>批量导入学生信息和成绩数据，支持Excel格式文件的导入与导出</p>
    </div>

    <!-- 导入导出区域 -->
    <el-card shadow="never" class="main-card">
      <el-tabs v-model="activeTab" class="data-tabs">
            <!-- 学生信息导入 - 仅管理员可见 -->
            <el-tab-pane v-if="isAdmin" name="student">
              <template #label>
                <span class="tab-label">
                  <el-icon><User /></el-icon>
                  学生信息导入
                </span>
              </template>
              <div class="tab-content">
                <el-alert
                  title="学生信息导入格式说明"
                  type="info"
                  :closable="false"
                  show-icon
                >
                  <div class="format-guide">
                    <div class="guide-section">
                      <h4> Excel格式要求（按列顺序）：</h4>
                      <table class="format-table">
                        <tr>
                          <th>列</th>
                          <th>字段名</th>
                          <th>必填</th>
                          <th>格式要求</th>
                          <th>示例</th>
                        </tr>
                        <tr>
                          <td>A</td>
                          <td>学号</td>
                          <td><el-tag type="danger" size="small">必填</el-tag></td>
                          <td>文本，唯一</td>
                          <td>2024001</td>
                        </tr>
                        <tr>
                          <td>B</td>
                          <td>姓名</td>
                          <td><el-tag type="danger" size="small">必填</el-tag></td>
                          <td>文本</td>
                          <td>张三</td>
                        </tr>
                        <tr>
                          <td>C</td>
                          <td>性别</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td><strong>只能是"男"或"女"</strong></td>
                          <td>男</td>
                        </tr>
                        <tr>
                          <td>D</td>
                          <td>出生日期</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td><strong>yyyy-MM-dd</strong></td>
                          <td>2005-03-15</td>
                        </tr>
                        <tr>
                          <td>E</td>
                          <td>入学日期</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td><strong>yyyy-MM-dd</strong></td>
                          <td>2024-09-01</td>
                        </tr>
                        <tr>
                          <td>F</td>
                          <td>院系</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>必须在系统中存在</td>
                          <td>计算机学院</td>
                        </tr>
                        <tr>
                          <td>G</td>
                          <td>班级</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>必须在系统中存在</td>
                          <td>计算机1班</td>
                        </tr>
                        <tr>
                          <td>H</td>
                          <td>学籍状态</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>在籍/休学/毕业/退学</td>
                          <td>在籍</td>
                        </tr>
                        <tr>
                          <td>I</td>
                          <td>备注</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>任意文本</td>
                          <td>优秀学生</td>
                        </tr>
                      </table>
                    </div>
                    
                    <div class="guide-section">
                      <h4>重要提示：</h4>
                      <ul class="tips-list">
                        <li><strong>性别格式</strong>：必须是中文"男"或"女"，不能是"M"、"F"、"1"、"2"</li>
                        <li><strong>日期格式</strong>：必须是 yyyy-MM-dd 格式（如：2005-03-15），不能用斜杠或其他格式</li>
                        <li><strong>学号处理</strong>：如果学号已存在则覆盖更新，不存在则新建</li>
                        <li><strong>院系班级</strong>：Excel中的院系和班级名称必须与系统中的完全一致</li>
                        <li><strong>学籍状态</strong>：只能是"在籍"、"休学"、"毕业"、"退学"四选一</li>
                      </ul>
                    </div>
                    
                    <div class="guide-section">
                      <h4>导入步骤：</h4>
                      <ol class="tips-list">
                        <li>点击下方"下载学生信息模板"按钮获取标准模板（含测试样例）</li>
                        <li>按照模板格式填写学生信息（可保留或删除测试样例）</li>
                        <li>确保院系和班级在系统中已存在（在院系管理和班级管理中创建）</li>
                        <li>检查数据格式，确保性别、日期等格式正确</li>
                        <li>上传Excel文件，等待导入完成</li>
                      </ol>
                    </div>
                    
                    <div class="guide-section">
                      <h4>✅ 导入后自动处理：</h4>
                      <ul class="tips-list">
                        <li><strong>新建学生</strong>：自动创建登录账号，用户名为学号，默认密码123456</li>
                        <li><strong>更新学生</strong>：更新学生信息和姓名，保留原密码不变</li>
                        <li>账号角色：学生</li>
                        <li>提示：可以用此功能批量更新学生信息</li>
                      </ul>
                    </div>
                  </div>
                </el-alert>

                <el-button 
                  type="primary" 
                  plain 
                  @click="downloadTemplate('student')"
                  style="margin: 20px 0"
                >
                  <el-icon><Download /></el-icon>
                  下载学生信息模板
                </el-button>

                <el-upload
                  class="upload-demo"
                  drag
                  action="#"
                  :http-request="handleStudentUpload"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  accept=".xlsx,.xls"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </el-upload>
              </div>
            </el-tab-pane>

            <!-- 成绩导入 -->
            <el-tab-pane name="score">
              <template #label>
                <span class="tab-label">
                  <el-icon><Medal /></el-icon>
                  成绩数据导入
                </span>
              </template>
              <div class="tab-content">
                <el-alert
                  title="成绩数据导入格式说明"
                  type="info"
                  :closable="false"
                  show-icon
                >
                  <div class="format-guide">
                    <div class="guide-section">
                      <h4>Excel格式要求（按列顺序）：</h4>
                      <table class="format-table">
                        <tr>
                          <th>列</th>
                          <th>字段名</th>
                          <th>必填</th>
                          <th>格式要求</th>
                          <th>示例</th>
                        </tr>
                        <tr>
                          <td>A</td>
                          <td>学号</td>
                          <td><el-tag type="danger" size="small">必填</el-tag></td>
                          <td>必须在系统中存在</td>
                          <td>2024001</td>
                        </tr>
                        <tr>
                          <td>B</td>
                          <td>姓名</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>仅供参考</td>
                          <td>张三</td>
                        </tr>
                        <tr>
                          <td>C</td>
                          <td>课程名称</td>
                          <td><el-tag type="danger" size="small">必填</el-tag></td>
                          <td>文本</td>
                          <td>高等数学</td>
                        </tr>
                        <tr>
                          <td>D</td>
                          <td>成绩</td>
                          <td><el-tag type="danger" size="small">必填</el-tag></td>
                          <td><strong>数字：0-100</strong></td>
                          <td>92</td>
                        </tr>
                        <tr>
                          <td>E</td>
                          <td>学分</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td><strong>数字：0-10</strong></td>
                          <td>4.0</td>
                        </tr>
                        <tr>
                          <td>F</td>
                          <td>学期</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td><strong>格式：2023-2024第一学期</strong></td>
                          <td>2024-2025第一学期</td>
                        </tr>
                        <tr>
                          <td>G</td>
                          <td>考试类型</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>期末/期中/平时</td>
                          <td>期末考试</td>
                        </tr>
                        <tr>
                          <td>H</td>
                          <td>备注</td>
                          <td><el-tag size="small">选填</el-tag></td>
                          <td>任意文本</td>
                          <td>优秀</td>
                        </tr>
                      </table>
                    </div>
                    
                    <div class="guide-section">
                      <h4>重要提示：</h4>
                      <ul class="tips-list">
                        <li><strong>学号必须存在</strong>：导入的学号必须是系统中已有的学生</li>
                        <li><strong>成绩格式</strong>：必须是纯数字，范围0-100</li>
                        <li><strong>学分格式</strong>：必须是数字，范围0-10，可以是小数</li>
                        <li><strong>学期格式</strong>：建议格式"2023-2024第一学期"或"2023-2024第二学期"</li>
                        <li><strong>覆盖更新</strong>：如果学生的该课程成绩已存在，导入时会自动覆盖更新</li>
                      </ul>
                    </div>
                  </div>
                </el-alert>

                <el-button 
                  type="primary" 
                  plain 
                  @click="downloadTemplate('score')"
                  style="margin: 20px 0"
                >
                  <el-icon><Download /></el-icon>
                  下载成绩数据模板
                </el-button>

                <el-upload
                  class="upload-demo"
                  drag
                  action="#"
                  :http-request="handleScoreUpload"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                  accept=".xlsx,.xls"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                </el-upload>
              </div>
            </el-tab-pane>

            <!-- 导入历史 -->
            <el-tab-pane name="history">
              <template #label>
                <span class="tab-label">
                  <el-icon><Files /></el-icon>
                  导入历史
                </span>
              </template>
              <div class="tab-content">
                <div class="history-section">
                  <div class="history-header">
                    <span class="history-count">共 {{ total }} 条记录</span>
                    <el-button size="small" @click="fetchHistory" :icon="Refresh">
                      刷新
                    </el-button>
                  </div>

                  <el-table :data="historyData" v-loading="loading" border style="margin-top: 16px">
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="type" label="导入类型" width="120">
                      <template #default="{ row }">
                        <el-tag :type="row.type === 'student' ? '' : 'success'">
                          {{ row.type === 'student' ? '学生信息' : '成绩数据' }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="fileName" label="文件名" min-width="200" />
                    <el-table-column prop="totalCount" label="总数" width="100" align="center" />
                    <el-table-column prop="successCount" label="成功" width="100" align="center">
                      <template #default="{ row }">
                        <span style="color: #67c23a; font-weight: bold">{{ row.successCount }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="failCount" label="失败" width="100" align="center">
                      <template #default="{ row }">
                        <span style="color: #f56c6c; font-weight: bold">{{ row.failCount }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                      <template #default="{ row }">
                        <el-tag :type="getStatusTag(row.status)">
                          {{ getStatusText(row.status) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="导入时间" width="180" />
                    <el-table-column label="操作" width="100" fixed="right">
                      <template #default="{ row }">
                        <el-button link type="primary" size="small" @click="handleViewDetail(row)">
                          查看详情
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <div class="pagination-container">
                    <el-pagination
                      v-model:current-page="historyQuery.current"
                      v-model:page-size="historyQuery.size"
                      :page-sizes="[10, 20, 50, 100]"
                      :total="total"
                      layout="total, sizes, prev, pager, next, jumper"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 数据导出 -->
            <el-tab-pane name="export">
              <template #label>
                <span class="tab-label">
                  <el-icon><Download /></el-icon>
                  数据导出
                </span>
              </template>
              <div class="tab-content">
                <div class="export-section">
            <!-- 学生信息导出 -->
            <div class="export-item">
              <div class="export-info">
                <el-icon class="export-icon" color="#409EFF"><User /></el-icon>
                <div>
                  <div class="export-title">学生信息导出</div>
                  <div class="export-desc">导出所有学生的基本信息和学籍状态</div>
                </div>
              </div>
              <el-button type="primary" @click="handleExport('student')">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>

            <el-divider />

            <!-- 成绩数据导出 -->
            <div class="export-item">
              <div class="export-info">
                <el-icon class="export-icon" color="#67C23A"><Medal /></el-icon>
                <div>
                  <div class="export-title">成绩数据导出</div>
                  <div class="export-desc">导出学生的成绩记录和学分信息</div>
                </div>
              </div>
              <el-select 
                v-model="exportForm.semester" 
                placeholder="选择学期" 
                style="width: 180px; margin-right: 10px"
              >
                <el-option label="2024-2025-1" value="2024-2025-1" />
                <el-option label="2023-2024-2" value="2023-2024-2" />
                <el-option label="2023-2024-1" value="2023-2024-1" />
              </el-select>
              <el-button type="success" @click="handleExport('score')">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>

            <el-divider />

            <!-- 学籍汇总导出 -->
            <div class="export-item">
              <div class="export-info">
                <el-icon class="export-icon" color="#E6A23C"><Document /></el-icon>
                <div>
                  <div class="export-title">学籍汇总表</div>
                  <div class="export-desc">导出学籍状态统计和院系分布</div>
                </div>
              </div>
              <el-button type="warning" @click="handleExport('summary')">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>

            <el-divider />

            <!-- 档案记录导出 -->
            <div class="export-item">
              <div class="export-info">
                <el-icon class="export-icon" color="#F56C6C"><Files /></el-icon>
                <div>
                  <div class="export-title">档案记录导出</div>
                  <div class="export-desc">导出学生的奖惩记录和学籍异动</div>
                </div>
              </div>
              <el-button type="danger" @click="handleExport('record')">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>

            <el-divider />

            <!-- 毕业档案包 -->
            <div class="export-item">
              <div class="export-info">
                <el-icon class="export-icon" color="#909399"><FolderOpened /></el-icon>
                <div>
                  <div class="export-title">毕业档案包</div>
                  <div class="export-desc">打包下载学生的完整档案（含成绩单、记录等）</div>
                </div>
              </div>
              <el-input 
                v-model="exportForm.studentNo" 
                placeholder="输入学号" 
                style="width: 180px; margin-right: 10px"
              />
              <el-button type="info" @click="handleExport('package')">
                <el-icon><Download /></el-icon>
                打包下载
              </el-button>
            </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, 
  Refresh, 
  User, 
  Medal, 
  Document, 
  Files, 
  FolderOpened,
  UploadFilled
} from '@element-plus/icons-vue'
import { 
  importStudent, 
  importScore, 
  getImportHistory,
  downloadTemplate as downloadTemplateAPI,
  exportStudent,
  exportScore,
  exportSummary,
  exportRecord,
  exportPackage
} from '@/api/import-export'
import { useUserStore } from '@/store/user'

// 用户信息
const userStore = useUserStore()
const isAdmin = computed(() => userStore.userInfo?.roleCode === 'admin')

// Tab - 根据角色设置默认tab
const activeTab = ref('')

// 监听tab切换
watch(activeTab, (newTab) => {
  if (newTab === 'history') {
    fetchHistory()
  }
})

onMounted(() => {
  // 管理员默认显示学生信息，教师默认显示成绩数据
  activeTab.value = isAdmin.value ? 'student' : 'score'
})

// 导出表单
const exportForm = reactive({
  semester: '',
  studentNo: ''
})

// 导入历史
const historyData = ref<any[]>([])
const loading = ref(false)
const total = ref(0)

// 分页查询参数
const historyQuery = reactive({
  current: 1,
  size: 10
})

// 下载模板
const downloadTemplate = (type: string) => {
  try {
    downloadTemplateAPI(type)
    ElMessage.success(`正在下载${type === 'student' ? '学生信息' : '成绩数据'}模板...`)
  } catch (error) {
    console.error('下载模板失败', error)
    ElMessage.error('下载模板失败')
  }
}

// 文件上传前验证
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件！')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB！')
    return false
  }
  return true
}

// 学生信息上传
const handleStudentUpload = async (options: any) => {
  const file = options.file
  const loading = ElMessage.info({
    message: '📤 正在导入数据，请稍候...',
    duration: 0,
    showClose: false
  })

  try {
    const response = await importStudent(file)
    loading.close()
    
    // 刷新历史记录
    await fetchHistory()
    
    // 立即显示导入结果
    showImportResult(response.data, '学生信息')
  } catch (error: any) {
    loading.close()
    console.error('导入失败', error)
    
    // 显示详细的错误信息
    const errorMsg = error?.response?.data?.msg || error?.message || '导入失败，请检查文件格式'
    ElMessage.error({
      message: `❌ 导入失败：${errorMsg}`,
      duration: 5000
    })
  }
}

// 成绩数据上传
const handleScoreUpload = async (options: any) => {
  const file = options.file
  const loading = ElMessage.info({
    message: '📤 正在导入数据，请稍候...',
    duration: 0,
    showClose: false
  })

  try {
    const response = await importScore(file)
    loading.close()
    
    // 刷新历史记录
    await fetchHistory()
    
    // 立即显示导入结果
    showImportResult(response.data, '成绩数据')
  } catch (error: any) {
    loading.close()
    console.error('导入失败', error)
    
    // 显示详细的错误信息
    const errorMsg = error?.response?.data?.msg || error?.message || '导入失败，请检查文件格式'
    ElMessage.error({
      message: `❌ 导入失败：${errorMsg}`,
      duration: 5000
    })
  }
}

// 数据导出
const handleExport = (type: string) => {
  try {
    switch (type) {
      case 'student':
        exportStudent()
        ElMessage.success('正在导出学生信息...')
        break
      case 'score':
        if (!exportForm.semester) {
          ElMessage.warning('请选择学期')
          return
        }
        exportScore(exportForm.semester)
        ElMessage.success(`正在导出${exportForm.semester}学期成绩...`)
        break
      case 'summary':
        exportSummary()
        ElMessage.success('正在生成学籍汇总表...')
        break
      case 'record':
        exportRecord()
        ElMessage.success('正在导出档案记录...')
        break
      case 'package':
        if (!exportForm.studentNo) {
          ElMessage.warning('请输入学号')
          return
        }
        exportPackage(exportForm.studentNo)
        ElMessage.success(`正在打包${exportForm.studentNo}的毕业档案...`)
        break
    }
  } catch (error) {
    console.error('导出失败', error)
    ElMessage.error('导出失败')
  }
}

// 获取导入历史
const fetchHistory = async () => {
  loading.value = true
  try {
    const data = await getImportHistory()
    if (Array.isArray(data)) {
      // 如果返回的是数组，进行前端分页
      total.value = data.length
      const start = (historyQuery.current - 1) * historyQuery.size
      const end = start + historyQuery.size
      historyData.value = data.slice(start, end)
    } else if (data && data.records) {
      // 如果返回的是分页对象
      historyData.value = data.records
      total.value = data.total
    } else {
      historyData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取导入历史失败', error)
    ElMessage.error('获取导入历史失败')
  } finally {
    loading.value = false
  }
}

// 页码改变
const handleCurrentChange = () => {
  fetchHistory()
}

// 每页条数改变
const handleSizeChange = () => {
  historyQuery.current = 1
  fetchHistory()
}

// 状态文本
const getStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: '导入中',
    1: '已完成',
    2: '失败'
  }
  return map[status] || '未知'
}

// 状态标签
const getStatusTag = (status: number) => {
  const map: Record<number, string> = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[status] || ''
}

// 查看详情
const handleViewDetail = (row: any) => {
  const successRate = row.totalCount > 0 
    ? ((row.successCount / row.totalCount) * 100).toFixed(1) 
    : 0
    
  let statusColor = '#67c23a'
  let statusBg = '#f0f9ff'
  let statusText = '导入成功'
  
  if (row.failCount > 0 && row.successCount > 0) {
    statusColor = '#e6a23c'
    statusBg = '#fdf6ec'
    statusText = '部分成功'
  } else if (row.failCount === row.totalCount) {
    statusColor = '#f56c6c'
    statusBg = '#fef0f0'
    statusText = '导入失败'
  }
  
  ElMessageBox.alert(`
    <div style="padding: 15px;">
      <!-- 状态栏 -->
      <div style="margin-bottom: 20px; padding: 15px; background: ${statusBg}; border-left: 4px solid ${statusColor}; border-radius: 4px;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <h4 style="margin: 0; color: ${statusColor}; font-size: 16px; font-weight: 600;">
            ${statusText}
          </h4>
          <span style="font-size: 18px; font-weight: bold; color: ${statusColor};">
            成功率：${successRate}%
          </span>
        </div>
      </div>
      
      <!-- 基本信息 -->
      <div style="margin-bottom: 20px;">
        <table style="width: 100%; border-collapse: collapse;">
          <tr style="border-bottom: 1px solid #ebeef5;">
            <td style="padding: 10px 0; color: #909399; width: 100px;">导入类型</td>
            <td style="padding: 10px 0; color: #303133; font-weight: 500;">${row.type === 'student' ? '学生信息' : '成绩信息'}</td>
          </tr>
          <tr style="border-bottom: 1px solid #ebeef5;">
            <td style="padding: 10px 0; color: #909399;">导入时间</td>
            <td style="padding: 10px 0; color: #303133;">${row.createTime || '未知'}</td>
          </tr>
          <tr style="border-bottom: 1px solid #ebeef5;">
            <td style="padding: 10px 0; color: #909399;">文件名称</td>
            <td style="padding: 10px 0; color: #303133;">${row.fileName || '未知'}</td>
          </tr>
          <tr>
            <td style="padding: 10px 0; color: #909399;">操作人</td>
            <td style="padding: 10px 0; color: #303133;">${row.operatorName || '未知'}</td>
          </tr>
        </table>
      </div>
      
      <!-- 统计数据 -->
      <div style="display: flex; gap: 12px; margin-bottom: 20px;">
        <div style="flex: 1; padding: 12px; background: #f5f7fa; border-radius: 4px; text-align: center;">
          <div style="color: #909399; font-size: 13px; margin-bottom: 5px;">总记录数</div>
          <div style="color: #303133; font-size: 20px; font-weight: bold;">${row.totalCount || 0}</div>
        </div>
        <div style="flex: 1; padding: 12px; background: #f0f9ff; border-radius: 4px; text-align: center;">
          <div style="color: #909399; font-size: 13px; margin-bottom: 5px;">成功数</div>
          <div style="color: #67c23a; font-size: 20px; font-weight: bold;">${row.successCount || 0}</div>
        </div>
        <div style="flex: 1; padding: 12px; background: #fef0f0; border-radius: 4px; text-align: center;">
          <div style="color: #909399; font-size: 13px; margin-bottom: 5px;">失败数</div>
          <div style="color: #f56c6c; font-size: 20px; font-weight: bold;">${row.failCount || 0}</div>
        </div>
      </div>
      
      ${row.failCount > 0 ? `
        <div style="padding: 12px; background: #fef0f0; border-left: 4px solid #f56c6c; border-radius: 4px;">
          <div style="color: #f56c6c; font-weight: 600; margin-bottom: 8px;">失败提示</div>
          <div style="color: #606266; font-size: 14px; line-height: 1.6;">
            共有 <b style="color: #f56c6c;">${row.failCount}</b> 条记录导入失败<br/>
            失败原因可能包括：数据格式错误、必填项缺失、关联数据不存在等
          </div>
        </div>
      ` : ''}
      
      ${row.errorMsg ? `
        <div style="margin-top: 12px; padding: 12px; background: #fef0f0; border-left: 4px solid #f56c6c; border-radius: 4px;">
          <div style="color: #f56c6c; font-weight: 600; margin-bottom: 8px;">系统错误</div>
          <div style="color: #606266; font-size: 14px;">${row.errorMsg}</div>
        </div>
      ` : ''}
    </div>
  `, '导入详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭',
    customClass: 'import-detail-dialog'
  })
}


// 显示导入结果
const showImportResult = (result: any, dataType: string) => {
  const { totalCount, successCount, failCount, successRate, failDetails } = result
  
  // 构建失败详情HTML - 简化显示
  let failDetailsHtml = ''
  if (failCount > 0) {
    // 动态生成失败行列表
    let failRowsHtml = ''
    if (failDetails && failDetails.length > 0) {
      failRowsHtml = failDetails.map((detail: any) => `
        <div style="padding: 12px 15px; background: #fff; border-left: 3px solid #f56c6c; margin-bottom: 10px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
          <div style="display: flex; justify-content: space-between; align-items: flex-start;">
            <div style="flex: 1;">
              <span style="display: inline-block; padding: 2px 8px; background: #f56c6c; color: white; border-radius: 3px; font-size: 13px; font-weight: bold; margin-right: 10px;">第 ${detail.rowNumber} 行</span>
              ${detail.studentNo ? `<span style="color: #606266; font-size: 14px;">学号：${detail.studentNo}</span>` : ''}
              ${detail.name ? `<span style="color: #606266; font-size: 14px; margin-left: 10px;">姓名：${detail.name}</span>` : ''}
            </div>
          </div>
          ${detail.errorReason ? `
            <div style="margin-top: 8px; color: #f56c6c; font-size: 14px;">
              <span style="font-weight: 500;">❌ ${detail.errorReason}</span>
            </div>
          ` : ''}
        </div>
      `).join('')
    }
    
    failDetailsHtml = `
      <div style="margin-top: 20px;">
        <div style="background: #fef0f0; padding: 15px; border-radius: 8px; border: 1px solid #f56c6c;">
          <h4 style="margin: 0 0 15px 0; color: #f56c6c; font-size: 16px; font-weight: 600;">
            ⚠️ 失败数据详情（共 ${failCount} 行出错${failDetails && failDetails.length < failCount ? `，显示前 ${failDetails.length} 条` : ''}）
          </h4>
          <div style="max-height: 400px; overflow-y: auto;">
            ${failRowsHtml || '<p style="margin: 0; color: #909399;">暂无详细错误信息</p>'}
          </div>
          ${failCount > (failDetails?.length || 0) ? `
            <div style="margin-top: 15px; padding: 10px; background: #fffbe6; border-radius: 4px; border-left: 3px solid #e6a23c;">
              <p style="margin: 0; font-size: 14px; color: #606266;">
                还有 <b style="color: #e6a23c;">${failCount - (failDetails?.length || 0)}</b> 条失败数据未显示
              </p>
            </div>
          ` : ''}
        </div>
      </div>
    `
  }
  
  // 确定状态
  let statusColor = '#67c23a'
  let statusIcon = '✅'
  let statusText = '导入成功'
  
  if (failCount === totalCount) {
    statusColor = '#f56c6c'
    statusIcon = '❌'
    statusText = '导入失败'
  } else if (failCount > 0) {
    statusColor = '#e6a23c'
    statusIcon = '⚠️'
    statusText = '部分成功'
  }
  
  // 显示结果对话框 - 简洁设计
  ElMessageBox.alert(`
    <div style="padding: 10px;">
      <!-- 顶部状态 -->
      <div style="text-align: center; padding: 25px; background: #f5f7fa; border-radius: 8px; margin-bottom: 20px;">
        <div style="font-size: 56px; margin-bottom: 15px;">${statusIcon}</div>
        <h2 style="margin: 0 0 10px 0; color: ${statusColor}; font-size: 26px; font-weight: 600;">
          ${statusText}
        </h2>
        <p style="margin: 0; font-size: 40px; font-weight: 700; color: ${statusColor};">
          ${successRate}%
        </p>
        <p style="margin: 5px 0 0 0; font-size: 14px; color: #909399;">导入成功率</p>
      </div>
      
      <!-- 统计数据 -->
      <div style="display: flex; gap: 15px; margin-bottom: 20px;">
        <div style="flex: 1; text-align: center; padding: 20px; background: #f0f9ff; border-radius: 8px; border: 2px solid #409eff;">
          <p style="margin: 0 0 8px 0; font-size: 14px; color: #606266;">总记录数</p>
          <p style="margin: 0; font-size: 32px; font-weight: bold; color: #303133;">${totalCount}</p>
        </div>
        <div style="flex: 1; text-align: center; padding: 20px; background: #f0f9ff; border-radius: 8px; border: 2px solid #67c23a;">
          <p style="margin: 0 0 8px 0; font-size: 14px; color: #606266;">成功导入</p>
          <p style="margin: 0; font-size: 32px; font-weight: bold; color: #67c23a;">${successCount}</p>
        </div>
        <div style="flex: 1; text-align: center; padding: 20px; background: #fef0f0; border-radius: 8px; border: 2px solid #f56c6c;">
          <p style="margin: 0 0 8px 0; font-size: 14px; color: #606266;">导入失败</p>
          <p style="margin: 0; font-size: 32px; font-weight: bold; color: #f56c6c;">${failCount}</p>
        </div>
      </div>
      
      ${failDetailsHtml}
      
      ${failCount === 0 ? `
        <div style="margin-top: 20px; padding: 20px; background: #f0f9ff; border-radius: 8px; text-align: center; border: 2px solid #67c23a;">
          <p style="margin: 0; color: #67c23a; font-size: 18px; font-weight: 600;">🎉 恭喜！所有数据导入成功</p>
          <p style="margin: 8px 0 0 0; color: #909399; font-size: 14px;">
            <a href="${dataType === '学生信息' ? '/student/manage' : '/score'}" style="color: #409eff; text-decoration: none; font-weight: 500;">
              前往${dataType === '学生信息' ? '学生管理' : '成绩管理'}
            </a> 查看导入的数据
          </p>
        </div>
      ` : ''}
    </div>
  `, `📥 ${dataType}导入结果`, {
    dangerouslyUseHTMLString: true,
    confirmButtonText: failCount > 0 ? '知道了' : '关闭',
    customClass: 'import-result-dialog'
  })
}
</script>

<style scoped lang="scss">
.import-export-container {
  padding: 24px;
  background: #f5f7fa;

  // 页面头部
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
    
    p {
      margin: 0;
      font-size: 14px;
      color: #909399;
    }
  }

  // 主卡片
  .main-card {
    background: white;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    
    :deep(.el-card__body) {
      padding: 0;
    }
  }

  // 标签页样式
  .data-tabs {
    :deep(.el-tabs__header) {
      margin: 0;
      border-bottom: 1px solid #e4e7ed;
      padding: 0 24px;
    }

    :deep(.el-tabs__nav-wrap) {
      &::after {
        height: 1px;
        background-color: #e4e7ed;
      }
    }

    :deep(.el-tabs__item) {
      height: 56px;
      line-height: 56px;
      font-size: 14px;
      color: #606266;
      padding: 0 20px;

      &.is-active {
        color: #409eff;
        font-weight: 500;
      }

      &:hover {
        color: #409eff;
      }
    }

    :deep(.el-tabs__active-bar) {
      height: 2px;
      background-color: #409eff;
    }

    .tab-label {
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        font-size: 16px;
      }
    }
  }

  // 标签内容
  .tab-content {
    padding: 24px;

    // 操作按钮组
    :deep(.el-button) {
      &.el-button--primary {
        background-color: #409eff;
        border-color: #409eff;

        &.is-plain {
          background: #ecf5ff;
          border-color: #b3d8ff;
          color: #409eff;

          &:hover {
            background: #409eff;
            border-color: #409eff;
            color: white;
          }
        }
      }
    }

    // 上传区域
    .upload-demo {
      margin-top: 20px;

      :deep(.el-upload-dragger) {
        border: 2px dashed #dcdfe6;
        border-radius: 6px;
        background: #fafafa;
        padding: 40px 20px;
        transition: all 0.3s;

        &:hover {
          border-color: #409eff;
          background: #f5f7fa;
        }

        .el-icon--upload {
          font-size: 48px;
          color: #409eff;
          margin-bottom: 16px;
        }

        .el-upload__text {
          color: #606266;
          font-size: 14px;

          em {
            color: #409eff;
            font-style: normal;
          }
        }
      }
    }

    // 格式说明指南
    .format-guide {
      .guide-section {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        h4 {
          margin: 0 0 12px 0;
          font-size: 14px;
          font-weight: 600;
          color: #303133;
        }
        
        .format-table {
          width: 100%;
          border-collapse: collapse;
          font-size: 13px;
          margin-bottom: 15px;
          
          th, td {
            border: 1px solid #EBEEF5;
            padding: 8px 12px;
            text-align: left;
          }
          
          th {
            background-color: #F5F7FA;
            color: #606266;
            font-weight: 600;
          }
          
          tr:hover {
            background-color: #F5F7FA;
          }
          
          td:first-child {
            text-align: center;
            font-weight: 600;
            color: #909399;
          }
          
          strong {
            color: #E6A23C;
          }
        }
      }
    
      .tips-list {
        margin: 0;
        padding-left: 20px;
        
        li {
          margin: 8px 0;
          color: #606266;
          line-height: 1.6;
          
          strong {
            color: #303133;
            font-weight: 600;
          }
        }
      }
    }

    .upload-demo {
      margin-top: 20px;
    }
  }

  // 历史记录区域
  .history-section {
    .history-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      .history-count {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  // 导出区域
  .export-section {
    .export-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px;
      margin-bottom: 16px;
      background: #f9fafb;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      transition: all 0.2s;

      &:last-child {
        margin-bottom: 0;
      }

      &:hover {
        background: #f5f7fa;
        border-color: #c0c4cc;
      }

      .export-info {
        display: flex;
        align-items: center;
        gap: 16px;
        flex: 1;

        .export-icon {
          font-size: 32px;
        }

        .export-title {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }

        .export-desc {
          font-size: 13px;
          color: #909399;
        }
      }

      :deep(.el-select),
      :deep(.el-input) {
        .el-input__wrapper {
          background: white;
        }
      }

      :deep(.el-button) {
        margin-left: 8px;
      }
    }

    :deep(.el-divider) {
      margin: 0;
      display: none;
    }
  }

  // 表格样式
  :deep(.el-table) {
    font-size: 14px;

    th.el-table__cell {
      background: #fafafa;
      color: #606266;
      font-weight: 500;
    }

    .el-table__body tr:hover > td {
      background: #f5f7fa;
    }
  }
}

// Element Plus 组件样式覆盖
:deep(.el-upload-dragger) {
  padding: 40px;
}

:deep(.el-icon--upload) {
  font-size: 50px;
  color: #409EFF;
}

:deep(.el-alert__content) {
  width: 100%;
}

:deep(.el-alert__title) {
  font-size: 15px;
  font-weight: 600;
}

:deep(.el-card) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;

  &.is-never-shadow {
    box-shadow: none;
  }
}

// 导入结果对话框样式
:deep(.import-result-dialog) {
  width: 1000px !important;
  max-width: 96vw;
  
  .el-message-box__content {
    max-height: 75vh;
    overflow-y: auto;
    
    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f5f5f5;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #ccc;
      border-radius: 3px;
      
      &:hover {
        background: #999;
      }
    }
  }
  
  .el-message-box__header {
    padding: 20px 20px 15px;
    border-bottom: 1px solid #eee;
  }
  
  .el-message-box__title {
    font-size: 20px;
    font-weight: 600;
  }
  
  .el-message-box__btns {
    padding: 15px 20px 20px;
    
    .el-button {
      padding: 10px 24px;
      font-size: 15px;
      min-width: 100px;
    }
  }
}

// 详情对话框样式
:deep(.import-detail-dialog) {
  width: 650px !important;
  max-width: 90vw;
  
  .el-message-box__header {
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-message-box__title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
  
  .el-message-box__content {
    padding: 0;
  }
  
  .el-message-box__btns {
    padding: 12px 20px;
    border-top: 1px solid #ebeef5;
    
    .el-button {
      padding: 8px 20px;
      font-size: 14px;
    }
  }
}
</style>

